/**
 *  Copyright 2010 ShenYang voole Co. Ltd.
 *  All right reserved. 
 */
package com.dianning.web.taglib;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.Writer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.components.Component;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 功能描述:分页
 *
 * 创建日期 May 25, 2010
 *
 * @author zhangbaochao
 *
 * @version 1.0
 *
 */
public class Write extends Component {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(Write.class);

	public Write(ValueStack arg0) {
		super(arg0);
	}

	protected int length = 0;

	private String value;

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public boolean start(Writer writer) {
		boolean result = super.start(writer);

		if (value == null) {
			value = "top";
		} else if (altSyntax()) {
			if (value.startsWith("%{") && value.endsWith("}")) {
				value = value.substring(2, value.length() - 1);
			}
		}
		String content = (String) this.getStack().findValue(value);
		if(StringUtils.isBlank(content)){
			try {
				writer.write("");
			} catch (IOException e) {
				logger.error(e);
			}
	    }else{
		    content = content.replaceAll("<(S*?)[^>]*>.*?|<.*? />", "");
		    content = content.replaceAll("&nbsp;", "");
		    content = StringUtils.trimToEmpty(content);
		    if(length == 0){
		    	try {
					writer.write("");
				} catch (IOException e) {
					logger.error(e);
				}
		    }else{
		    	int len = content.length();
			    if(length>=len){
			    	try {
						writer.write(content);
					} catch (IOException e) {
						logger.error(e);
					}
			    }else{
			    	String s = content.substring(0, length-2);
			    	try {
						writer.write(s+ "..");
					} catch (IOException e) {
						logger.error(e);
					}
			    }
		    }
	    }
		return result;
	}
}
